package com.ihome.android.academy;

import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.ihome.android.EAActivity;
import com.ihome.android.EAApp;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.common.ConfigUtil;
import com.ihome.android.common.PathID;
import com.ihome.android.dl.core.DownloadHelper;
import com.ihome.android.dl.core.DownloadTask;
import com.ihome.android.dl.util.DLFileInfo;
import com.ihome.android.dl.util.DownloadValues;
import com.ihome.android.http.HttpKeys;
import com.ihome.android.image.CubeImageView;
import com.ihome.android.image.ImageLoader;
import com.ihome.android.image.ImageLoaderFactory;
import com.ihome.android.image.impl.DefaultImageLoadHandler;
import com.ihome.android.academy.R;
import com.ihome.android.market2.asynctask.GetAppDetailTask;
import com.ihome.android.market2.asynctask.GetAppUrlTask;
import com.ihome.android.market2.asynctask.InstallAppTask;
import com.ihome.android.market2.asynctask.SearchAppTask;
import com.ihome.android.market2.info.AppDetailInfo;
import com.ihome.android.market2.info.AppInfo;
import com.ihome.android.market2.view.DialogFactory;
import com.ihome.android.market2.view.GuessFavItem;
import com.ihome.android.market2.view.MyScrollView;
import com.ihome.android.market2.view.MyScrollView.ScrollListener;
import com.ihome.android.mod.LoginMod;
import com.ihome.android.util.AppUtils;
import com.ihome.android.util.BgInstallApk;
import com.ihome.android.util.Tools;
import com.ihome.android.util.Util;
import com.ihome.android.util.log.LogUtil;
import com.ihome.android.util.log.UserBehaviorLog;
import com.ihome.android.util.log.UserBehaviorLog.NotifyType;
import com.ihome.android.util.log.UserBehaviorLog.UserBehavior;

public class DetailActivity extends EAActivity implements OnClickListener {
	private String					TAG				= DetailActivity.class.getSimpleName();
	/** 应用图标 */
	@EAInjectView(id = R.id.app_image)
	private CubeImageView			appImage;
	/** 应用名称 */
	@EAInjectView(id = R.id.app_name)
	private TextView				appName;
	/** 应用版本号 */
	@EAInjectView(id = R.id.app_version)
	private TextView				appVersion;
	/** 应用分类 */
	@EAInjectView(id = R.id.app_type)
	private TextView				appType;
	/** 下载次数 */
	@EAInjectView(id = R.id.download_time)
	private TextView				downloadTimes;
	/** 线性下载进度条 */
	@EAInjectView(id = R.id.numberbar)
	private ProgressBar				numberbar;
	@EAInjectView(id = R.id.tv_dl_percent)
	private TextView				tv_dl_percent;
	/** 下载按钮 */
	@EAInjectView(id = R.id.btn_start_dl)
	private Button					btn_start_dl;
	/** 打开应用按钮 */
	@EAInjectView(id = R.id.btn_open_app)
	private Button					btn_open_app;
	/** 应用详情字符 */
	@EAInjectView(id = R.id.detail_contents)
	private TextView				detailContent;
	/** 应用截图字符 */
	@EAInjectView(id = R.id.preview_msg)
	private TextView				detailPreview;
	/** 应用详情内容 */
	@EAInjectView(id = R.id.detail_msg)
	private TextView				detailMsg;
	/** 应用详情内容 */
	@EAInjectView(id = R.id.sv_detail)
	private MyScrollView			sv_detail;
	/** 应用详情预览图左侧 */
	@EAInjectView(id = R.id.preview_left)
	private CubeImageView			previewLeft;
	/** 应用详情预览图右侧 */
	@EAInjectView(id = R.id.preview_right)
	private CubeImageView			previewRight;
	/** 猜您喜欢视图 */
	@EAInjectView(id = R.id.ll_guess)
	private LinearLayout			ll_guess;
	@EAInjectView(id = R.id.ll_data_tip)
	private TextView ll_data_tip;
	private List<AppInfo>			mRelativeAppList;

	private Handler					mHandler;
	private AppDetailInfo			mAppDetailInfo	= null;
	private static StringTokenizer	st;
	private ArrayList<String>		lstUrl			= new ArrayList<String>();
	/** 当前APP ID */
	private int						appID			= -1;
	/** 加载图片 */
	private ImageLoader				imageLoader;
	private String					appPkgName		= "";
	private String					keyword			= "";

	private void procHandler() {
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {

				DownloadTask task = null;
				if (msg.obj instanceof DownloadTask) {
					task = (DownloadTask) msg.obj;
				}

				switch (msg.what) {
				case DownloadValues.Types.ADD:
					LogUtil.d(TAG, "---procHandler() Types.ADD ----> FileName = " + task.getAppInfo().getFileName());
					break;

				case DownloadValues.Types.COMPLETE:
					LogUtil.d(TAG, "---procHandler() Types.COMPLETE ----> FileName = " + task.getAppInfo().getFileName());
					handleCompletedAction(task.getAppInfo());
					break;

				case DownloadValues.Types.PROCESS:
					String speed = task.getDownloadSpeed() + "kbps | " + Tools.formateFileSize(getApplication(), task.getDownloadSize()) + " / "
							+ Tools.formateFileSize(getApplication(), task.getTotalSize());
					String progress = task.getDownloadPercent() + "";
					LogUtil.d(TAG, "---procHandler() Types.PROCESS ---->  " + task.getAppInfo().getFileName() + "  ---> speed = " + speed + "; progress = " + progress);
					handleProgress(task.getAppInfo());
					break;

				case DownloadValues.Types.ERROR:
					handleError(task.getAppInfo(),task.getErrorCode(),task.getErrorInfo());
					break;

				default:
					break;
				}
			}
		};
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail_dialog);
		imageLoader = ImageLoaderFactory.create(this);
		((DefaultImageLoadHandler) imageLoader.getImageLoadHandler()).setLoadingResources(R.drawable.default_recomm_item);

		appID = getIntent().getExtras().getInt(HttpKeys.KEY_APPID);

		procHandler();
		initView();
		stepToDetail(getIntent());
		EAApp.getApp().addHandler(mHandler);

	}

	@Override
	protected void onNewIntent(Intent intent) {
		LogUtil.i(TAG, "--> onNewIntent()");
		super.onNewIntent(intent);
		stepToDetail(intent);
	}

	protected void onResume() {
		super.onResume();
	}

	private void initView() {
		btn_start_dl.setOnClickListener(this);
		btn_open_app.setOnClickListener(this);
		btn_start_dl.setNextFocusDownId(R.id.detail_contents);
		btn_open_app.setNextFocusDownId(R.id.detail_contents);

		detailContent.setOnFocusChangeListener(new DetailListener());
		detailPreview.setOnFocusChangeListener(new DetailListener());
		detailPreview.setNextFocusDownId(R.id.ll_guess);

		ll_guess.setOnFocusChangeListener(new OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				if (hasFocus) {
					ll_guess.getChildAt(0).requestFocus();
				}
			}
		});

		sv_detail.setScrollListener(new ScrollListener() {
			@Override
			public void scrolltobottom() {
				ll_guess.requestFocus();
				ll_guess.getChildAt(0).requestFocus();
			}

			@Override
			public void scrolltoTop() {
				detailContent.requestFocus();
			}
		});
	}

	public class DetailListener implements OnFocusChangeListener {
		public void onFocusChange(View v, boolean hasFocus) {
			if (hasFocus) {
				switch (v.getId()) {
				case R.id.detail_contents:
					showDetailMsg();
					break;
				case R.id.preview_msg:
					showPreview();
					break;
				default:
					break;
				}
			}
			else {
				switch (v.getId()) {
				case R.id.detail_contents:
					hidePreview();
					break;
				case R.id.preview_msg:
					hideDetailMsg();
					break;
				default:
					break;
				}
			}
		}
	}

	private void showDetailMsg() {
		sv_detail.setVisibility(View.VISIBLE);
		hidePreview();

		LogUtil.d(TAG, "scroll > range = " + sv_detail.getTotalVerticalScrollRange());
		LogUtil.d(TAG, "viewable > height = " + sv_detail.getHeight());
		if (sv_detail.getTotalVerticalScrollRange() <= sv_detail.getHeight()) {
			//does not scroll
			sv_detail.setFocusable(false);
			detailContent.setNextFocusDownId(R.id.ll_guess);
		}
		else {
			sv_detail.setFocusable(true);
			detailContent.setNextFocusDownId(R.id.sv_detail);
		}

	}

	private void hideDetailMsg() {
		if (sv_detail.getVisibility() == View.VISIBLE) {
			sv_detail.setVisibility(View.GONE);
		}
	}

	private void showPreview() {
		previewLeft.setVisibility(View.VISIBLE);
		previewRight.setVisibility(View.VISIBLE);
		hideDetailMsg();
	}

	private void hidePreview() {
		if (previewLeft.getVisibility() == View.VISIBLE) {
			previewLeft.setVisibility(View.GONE);
		}
		if (previewRight.getVisibility() == View.VISIBLE) {
			previewRight.setVisibility(View.GONE);
		}
	}

	private void stepToDetail(Intent intent) {
		Bundle b = intent.getExtras();
		if (b != null && b.containsKey(HttpKeys.KEY_PACKAGENAME)) {
			LogUtil.d(TAG, "getIntent().getExtras() Not NULL");
			appPkgName = "" + b.getString(HttpKeys.KEY_PACKAGENAME);
			keyword = "" + b.getString(HttpKeys.KEY_KEYWORD);
			LogUtil.d(TAG, "pkgName = " + appPkgName + "; keyword = " + keyword);
			appAuthLogin();
		}
		else {
			LogUtil.e(TAG, "getIntent().getExtras() is NULL");
			getAppDetail(appID);
		}
	}

	public void getAppDetail(int appID) {
		LogUtil.d(TAG, "------getAppDetail()------");
		this.appID = appID;
		Bundle b = new Bundle();
		b.putInt(HttpKeys.KEY_APPID, appID);
		b.putString(HttpKeys.KEY_PATHID, "");
		new GetAppDetailTask(DetailActivity.this).execute(b);
	}

	private void appAuthLogin() {
		LogUtil.d(TAG, "------appAuthLogin()------");
		if (TextUtils.isEmpty(ConfigUtil.SessionKey)) {
			if (!TextUtils.isEmpty(Util.getOTTUserName(this.getApplicationContext()))) {
				LoginMod.autoLogin(this);
			}
			else {
				LoginMod.autoRegister(this, "", false);
			}
		}
		else if (!TextUtils.isEmpty(keyword)) {
			LogUtil.d(TAG, "------appAuthLogin --> doSearch()------");
			doSearch();
		}
	}

	public void doSearch() {
		LogUtil.d(TAG, "------doSearch()------");
		Bundle bundle = new Bundle();
		bundle.putInt(HttpKeys.KEY_STARTINDEX, 0);
		bundle.putInt(HttpKeys.KEY_SORT, 0);
		bundle.putInt(HttpKeys.KEY_CHARGE, 0);
		bundle.putInt(HttpKeys.KEY_MAXNUM, 8);
		bundle.putString(HttpKeys.KEY_KEYWORD, keyword);
		bundle.putString(HttpKeys.KEY_PACKAGENAME, appPkgName);
		new SearchAppTask(DetailActivity.this).execute(bundle);
	}

	/**
	 * 应用详情数据请求成功后的回调方法, 填充页面数据
	 * 
	 * @param appDetailInfo
	 */
	public void fillUpAppDetailInfo(AppDetailInfo appDetailInfo) {
		this.mAppDetailInfo = appDetailInfo;
		LogUtil.v(TAG, "fillUpAppDetailInfo() --> RateStatus = " + mAppDetailInfo.getRateStatus());

		if (mAppDetailInfo == null) {
			return;
		}
		if (mAppDetailInfo != null && !TextUtils.isEmpty(mAppDetailInfo.getIconUrl())) {
			appID = mAppDetailInfo.getAppId();

			//gy:如何应用的图标加载
			appImage.loadImage(imageLoader, mAppDetailInfo.getIconUrl());
			appName.setText(mAppDetailInfo.getAppName());
			appVersion.setText(mAppDetailInfo.getVersion());
			appType.setText(mAppDetailInfo.getClsName());
			downloadTimes.setText(getString(R.string.app_detail_tip, mAppDetailInfo.getApkFileSize(), String.valueOf(mAppDetailInfo.getDownNum())));
			detailMsg.setText(mAppDetailInfo.getSynopsis());
		}

		if (mAppDetailInfo.getPreview() != null) {
			st = new StringTokenizer(mAppDetailInfo.getPreview(), ";");
			lstUrl.clear();
			while (st.hasMoreTokens()) {
				lstUrl.add(st.nextToken());
			}

			previewLeft.loadImage(imageLoader, lstUrl.get(0));
			previewRight.loadImage(imageLoader, lstUrl.get(1));
		}

		numberbar.setVisibility(View.GONE);
		tv_dl_percent.setVisibility(View.GONE);
		showDetailMsg();
		checkAppStatus();
	}

	/**
	 * 检测APP是否已安装
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void checkAppStatus() {
		if (AppUtils.checkAppInstallByPkgName(this, mAppDetailInfo.getPackageName())) {
			btn_start_dl.setVisibility(View.GONE);
			btn_open_app.setVisibility(View.VISIBLE);
			btn_open_app.requestFocus();
		}
		else {
			btn_start_dl.setVisibility(View.VISIBLE);
			btn_open_app.setVisibility(View.GONE);
			btn_start_dl.requestFocus();
			btn_start_dl.setEnabled(true);
		}
	}

	/**
	 * 关联应用数据请求成功后的回调方法
	 * 
	 * @param mListAppInfo
	 */
	public void fillUpAppRelative(List<AppInfo> mListAppInfo) {
		if (mListAppInfo != null) {
			mRelativeAppList = mListAppInfo;
			ll_guess.removeAllViews();
			for (int i = 0; i < mRelativeAppList.size() && i < 3; i++) {
				AppInfo info = mRelativeAppList.get(i);
				GuessFavItem guessFavItem = new GuessFavItem(this, imageLoader);
				guessFavItem.initView(info, i);
				guessFavItem.setTag(info);
				guessFavItem.setClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						AppInfo appInfo = (AppInfo) v.getTag();
						Bundle b = new Bundle();
						b.putInt(HttpKeys.KEY_APPID, Integer.parseInt(appInfo.getAppId()));
						b.putString(HttpKeys.KEY_PATHID, String.valueOf(PathID.RELATIVE_APP_PATH_ID) + "-" + appInfo.getAppId());
						new GetAppDetailTask(DetailActivity.this).execute(b);

						/** 用户行为统计 详情页“猜你喜欢”点击行为 */
						String[] msg1 = { "", "", "" + appID, "", "", "" };
						UserBehaviorLog.getInstance().writeLog(UserBehavior.CLICK_FAVI_GUESS, NotifyType.TYPE_NORMAL, "", msg1);

					}
				});

				ll_guess.addView(guessFavItem.getView());
			}
			
			if(mRelativeAppList.size()>0){
				ll_data_tip.setVisibility(View.GONE);
			}else{
				ll_data_tip.setVisibility(View.VISIBLE);
			}
		}
		
	}

	/**
	 * 文件下载完成
	 * 
	 * @param dLFileInfo
	 * @see [类、类#方法、类#成员]
	 */
	private void handleCompletedAction(DLFileInfo dLFileInfo) {
		btn_start_dl.setEnabled(false);

		String filePath = dLFileInfo.getFilePath() + dLFileInfo.getFileName();
		LogUtil.d(TAG, "Download CompletedAction ---> filePath = " + filePath);
		boolean isCurrentApp = false;
		if (mAppDetailInfo != null && dLFileInfo.getPkgName().equals(mAppDetailInfo.getPackageName())) {
			isCurrentApp = true;
		}

		if (EAApp.isSystemApp) {
			Bundle b = new Bundle();
			b.putString(HttpKeys.KEY_APKPATH, filePath);
			new InstallAppTask(DetailActivity.this, isCurrentApp).execute(b);
		}
		else {
			BgInstallApk.doInstallation(DetailActivity.this, filePath);
		}
	}

	/**
	 * 
	 * 根据下载后台服务，更新当前apk下载进度
	 * 
	 * @param dLFileInfo
	 * @param speed
	 * @param progress
	 * @see [类、类#方法、类#成员]
	 */
	private void handleProgress(DLFileInfo dLFileInfo) {
		numberbar.setProgress(dLFileInfo.getProgress());
		tv_dl_percent.setText(dLFileInfo.getProgress() + "%");
	}

	/**
	 * 
	 * 解决下载过程中的错误
	 * 
	 * @param dLFileInfo
	 */
	public void handleError(DLFileInfo dLFileInfo,int errorCode, String errorInfo) {
		new DialogFactory(this).showDialog(getString(R.string.attention_error), errorInfo);
	}
	
	/**
	 * 增加下载任务
	 */
	private void addDLFile(DLFileInfo dLFileInfo) {
		LogUtil.d(TAG, "Add DL File() --> = " + dLFileInfo.getFilePath() + dLFileInfo.getFileName());
		DownloadHelper.addNewTask(DetailActivity.this, dLFileInfo, new DownloadHelper.PreDownloadStatusListener() {

			@Override
			public void sdCardCannotWriteOrRead(int errorCode, String errorInfo) {
				Toast.makeText(DetailActivity.this, "不能读写SD卡", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void notFoundSDCard(int errorCode, String errorInfo) {
				Toast.makeText(DetailActivity.this, "没有SD卡", Toast.LENGTH_SHORT).show();
			}

			@Override
			public void moreTaskCount(int errorCode, String errorInfo) {
				Toast.makeText(DetailActivity.this, "任务列表已满", Toast.LENGTH_SHORT).show();
			}
		});
	}

	/**
	 * 
	 * 获取APK的下载URL
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	private void getDLUrl() {
		LogUtil.v(TAG, "startDL() -->");

		if (mAppDetailInfo != null) {
			Bundle b = new Bundle();
			b.putInt(HttpKeys.KEY_APPID, appID);
			b.putString(HttpKeys.KEY_APPNAME, mAppDetailInfo.getAppName());
			b.putString(HttpKeys.KEY_PACKAGENAME, mAppDetailInfo.getPackageName());
			new GetAppUrlTask(this).execute(b);

		}
		else {
			LogUtil.e(TAG, "getDLUrl() --> mAppDetailInfo is NULL");
		}

	}

	/**
	 * 
	 * 开始下载APK
	 * 
	 * @param apkurl
	 * @see [类、类#方法、类#成员]
	 */
	public void startDLAPK(String apkurl, String appName, String pkgName,String appMD5) {

		if (mAppDetailInfo != null) {
			btn_start_dl.setVisibility(View.INVISIBLE);
			numberbar.setVisibility(View.VISIBLE);
			tv_dl_percent.setVisibility(View.VISIBLE);
			numberbar.setProgress(0);
			tv_dl_percent.setText(0 + "%");

			DLFileInfo picFileInfo = new DLFileInfo();
			picFileInfo.setFilePath(ConfigUtil.FILE_PATH);
			picFileInfo.setFileUrl(apkurl);
			picFileInfo.setFileType("apk");
			picFileInfo.setPkgName(pkgName);
			picFileInfo.setFileName(appName + ".apk");
			picFileInfo.setIconUrl(mAppDetailInfo.getIconUrl());
			picFileInfo.setMD5(appMD5);
			addDLFile(picFileInfo);
		}
		else {
			LogUtil.e(TAG, "startDLAPK() --> mAppDetailInfo is NULL");
		}
	}

	@Override
	public void finish() {
		super.finish();
		EAApp.getApp().clearHandler(mHandler);
	}

	private void release() {
		if (mRelativeAppList != null) {
			mRelativeAppList = null;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		release();
		LogUtil.v(TAG, "onDestroy");
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_start_dl:
			getDLUrl();
			btn_start_dl.setEnabled(false);

			/** 用户行为统计 详情页应用安装点击行为 */
			String[] msg1 = { "", "", "" + appID, "", "", "" };
			UserBehaviorLog.getInstance().writeLog(UserBehavior.CLICK_INSTALL, NotifyType.TYPE_NORMAL, "", msg1);

			break;
		case R.id.btn_open_app:
			AppUtils.openApp(getApplicationContext(), mAppDetailInfo.getPackageName());

			/** 用户行为统计 详情页 打开应用点击行为 */
			String[] msg = { "", "", "" + appID, "", "", "" };
			UserBehaviorLog.getInstance().writeLog(UserBehavior.CLICK_OPEN, NotifyType.TYPE_NORMAL, "", msg);

			break;

		default:
			break;
		}
	}

	/**
	 * 应用安装成功后的回调方法，需要清除已安装列表
	 * 
	 * @see [类、类#方法、类#成员]
	 */
	public void installationCheck(String pkgName) {
		if (mAppDetailInfo != null && pkgName.equals(mAppDetailInfo.getPackageName())) {
			numberbar.setVisibility(View.GONE);
			tv_dl_percent.setVisibility(View.GONE);

			checkAppStatus();
		}
	}

}
